package com.xl.tools;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class CommonQrUtils {

    public static void main(String[] args) throws IOException {
        String prefix = "https://wx.chargeland.cn/yuanjicode?code=";
        String qrCode = "123123123\n14444444";
        for (String code : qrCode.split("\n")) {
            code = code.trim();
            File outFile = new File("D:/" + code + "_testqr.png");
            drawLogoQRCodeSize(Files.newInputStream(Paths.get("D:","jiyuan.png")), outFile, prefix.concat(code), "[扫一扫]启动充电");
        }
    }

    // 生成带logo的二维码图片
    public static BufferedImage drawLogoQRCodeSize(InputStream logo, File codeFile, String qrUrl, String note) {
        int w = 170;
        int h = 170;
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        int QRCOLOR = 0xFF000000; // 默认是黑色
        int BGWHITE = 0xFFFFFFFF; // 背景颜色
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
            private static final long serialVersionUID = 1L;

            {
                put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
                put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
                put(EncodeHintType.MARGIN, 0);
            }
        };
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, w, h, hints);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            Font font = new Font("楷体", Font.BOLD, 20);
            int textHeight = font.getSize();
            // 新的图片，把带logo的二维码下面加上文字
            BufferedImage outImage = new BufferedImage(w + 10, h + textHeight + 12, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg = outImage.createGraphics();
            //白色背景
            outg.setPaint(Color.white);
            outg.drawRect(0, 0, outImage.getWidth(), outImage.getHeight());
            outg.fillRect(0, 0, outImage.getWidth(), outImage.getHeight());
            // 画二维码到新的面板
            outg.drawImage(image, 5, 6, image.getWidth(), image.getHeight(), null);


            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            outg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            outg.setFont(font); // 字体、字型、字号
            int strWidth = outg.getFontMetrics().stringWidth(note);
            int height = image.getHeight();
            outg.drawString(note, (outImage.getWidth() - strWidth) / 2, height + textHeight + 5); // 画文字
//                drawString(note,10,height + textHeight + 5,2,outg);
            outg.dispose();
            outImage.flush();
            image = outImage;
            if (logo != null) {
                try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                    Thumbnails.of(logo).size(32, 32).toOutputStream(byteArrayOutputStream);
                    try (ByteArrayInputStream inputstr = new ByteArrayInputStream(byteArrayOutputStream.toByteArray())) {
                        logo = inputstr;
                        // 构建绘图对象
                        Graphics2D g = image.createGraphics();
                        // 读取Logo图片
                        BufferedImage logoImg = ImageIO.read(logo);
                        // 开始绘制logo图片
                        Rectangle rect = new Rectangle((outImage.getWidth() - logoImg.getWidth()) / 2 - 1, (h + 10 - logoImg.getHeight()) / 2 - 1, logoImg.getWidth() + 2, logoImg.getHeight() + 2);
                        g.fillRoundRect(rect.x, rect.y, rect.width, rect.height, 2, 2);
                        g.drawImage(logoImg, rect.x + 2, rect.y + 2, 32, 32, null);
                        g.dispose();
                        logoImg.flush();
                    }
                }
            }

            image.flush();
            if (codeFile != null) {
                codeFile.getParentFile().mkdirs();
                codeFile.createNewFile();
                ImageIO.write(image, "png", codeFile); // TODO
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }
}
